<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\model\AdminLogin;
use think\captcha\Captcha;
use think\facade\Session;
use think\facade\Cookie;

class Login extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $captcha = new Captcha();
        if (request()->isPost()) {
            $data['name'] = $request->param('name');
            $data['password'] = md5($request->param('password'));
            $code = $request->param('code');
            $remember = $request->param('remember');

            $token = make_token();    //生成token
            AdminLogin::where($data)->setField('token', $token);

            $user = AdminLogin::where($data)->find();
            if (!$user) {
                return redirect('/admin/login')->with('error', '账号或密码错误');
            }

            if (!$captcha->check($code)) {
                return redirect('/admin/login')->with('error', '验证码错误');
            }
            if ($remember) {
                Cookie::set('token', $user['token'], time() + 60 * 60 * 24 * 7, '/');
            } else {
                Cookie::set('token', $user['token'], null, '/');
            }

            Session::set('admin',$user);
//            $_SESSION['admin'] = $user;

            return redirect('/admin/index')->with('success', '恭喜登录成功');



        } else {

            return view('Login/login');
        }


    }



    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete()
    {
//        $_SESSION = array();
//        if (isset($_COOKIE[session_name()])) {
//            setcookie(session_name(), "", time() - 3600, "/");
//        }
//        session('user',null);
//        return redirect('/admin/login');
    }

    /***
     * 安全退出
     */
    public function logout()
    {
        Cookie::delete('token');
        return redirect('/admin/login');
    }
}
